package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    public String BasePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //获取上传文件的文件名
        String originalFilename = file.getOriginalFilename();
        //动态截取后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //通过UUID重新生成文件名
        String fileName = UUID.randomUUID().toString() + substring;
        //创建文件存储路径
        File file1 = new File(BasePath);
        //如果不存在则创建
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            //将文件存放到指定目录下
            file.transferTo(new File(BasePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //File 从指定路径读取文件
            FileInputStream fileInputStream = new FileInputStream(new File(BasePath + name));
            //通过response 获取输出流 写出数据给页面-》下载
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream, outputStream);
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
